<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Freelancer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FaceRecognitionCallbackController extends Controller
{
    public function notify(Request $request)
    {
        $payload = $request->all();
        Log::info('[FaceRecognition][Callback] 收到通知', $payload);

        $orderNo = $request->input('orderNo');
        $liveRate = (float) $request->input('liveRate', 0);
        $similarity = (float) $request->input('similarity', 0);

        if (! $orderNo) {
            Log::warning('[FaceRecognition][Callback] 缺少 orderNo');
            return response()->json([
                'success' => false,
                'msg' => '处理失败',
            ]);
        }

        $freelancer = Freelancer::find($orderNo);
        if (! $freelancer) {
            Log::warning('[FaceRecognition][Callback] 未找到对应自由职业者', ['orderNo' => $orderNo]);
            return response()->json([
                'success' => false,
                'msg' => '处理失败',
            ]);
        }

        $status = ($liveRate > 90 && $similarity > 90)
            ? Freelancer::RECOGNITION_APPROVED
            : Freelancer::RECOGNITION_REJECTED;

        $freelancer->face_recognition_status = $status;
        $freelancer->save();

        Log::info('[FaceRecognition][Callback] 状态更新完成', [
            'freelancer_id' => $freelancer->id,
            'status' => $status,
            'liveRate' => $liveRate,
            'similarity' => $similarity,
        ]);

        return response()->json([
            'success' => true,
            'msg' => '处理成功',
        ]);
    }
}
